package com.pubinfo.passbook.data.controller;

import com.pubinfo.passbook.common.entity.TAutoTask;
import com.pubinfo.passbook.common.model.constant.TaskStatusEnum;
import com.pubinfo.passbook.common.model.vo.base.JsonResult;
import com.pubinfo.passbook.common.service.master.TAutoTaskService;
import com.pubinfo.passbook.data.quartz.service.TaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "task")
@Api(tags = "定时任务管理")
@Slf4j
public class AutoTaskController {
  @Autowired
  TAutoTaskService autoTaskService;
  
  @Autowired
  TaskService taskService;
  
  @GetMapping("/changeStatus/{id}")
  @ApiOperation(value = "改变任务状态")
  public JsonResult<Boolean> changeStatus(@PathVariable("id") String id) {
    return JsonResult.success(taskService.changeStatus(id));
  }
  
  /**
   * 立即运行
   */

  @GetMapping("/run/{id}")
  @ApiOperation(value = "")
  public JsonResult<String> run(@PathVariable("id") String id) {
    TAutoTask taskServer = autoTaskService.getById(id);
  
    if (TaskStatusEnum.STOP.getCode().equals(taskServer.getStatus())) {
      return JsonResult.error("立即执行请先开启任务");
    }
    taskService.run(taskServer);
    return JsonResult.success("ok");
  }
  
  /**
   * 删除
   */
  
  @PostMapping("/removeBatch")
  @ApiOperation(value = "")
  public JsonResult<String> removeBatch(@RequestParam("ids[]") String[] ids) {
    for (String id : ids) {
      TAutoTask autoJob = autoTaskService.getById(id);
      if (TaskStatusEnum.RUNNING.getCode().equals(autoJob.getStatus())) {
        return JsonResult.error("删除前请先停止任务！");
      }
    }
    taskService.removeBatch(ids);
    return JsonResult.success("ok");
  }
}
